package com.oc.mba.dao.impl;

import java.sql.Timestamp;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.oc.mba.controller.BackendController;
import com.oc.mba.dao.BaseDAOHibernate;
import com.oc.mba.dao.OcDevicesDAO;
import com.oc.mba.entity.OcDevices;
import com.oc.mba.util.CommLog;

@Repository
public class OcDevicesDAOImpl extends BaseDAOHibernate implements OcDevicesDAO {

	private static final CommLog logger = new CommLog(OcDevicesDAOImpl.class);
	@Override
	public int presistDevice(String imei, String androidID) {
		OcDevices device = null;
		// 通过AndroidID取得登记记录
		device = findByAndroidID(androidID);
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		// 如果不存在设备，保存设备信息
		if (device == null) {
			device = new OcDevices();
			device.setImei(imei);
			device.setAid(androidID);
			device.setLevel((short)0);
			device.setCreated(timestamp);
			device.setUpdated(timestamp);
		}
		// 存在设备返回设备ID
		else {
			return device.getId();
		}
		return (Integer) getHibernateTemplate().save(device);
	}
	
	@Override
	public OcDevices findById(int id) {
		try {
			OcDevices instance = (OcDevices) getHibernateTemplate().get("com.oc.mba.entity.OcDevices", id);
			return instance;
		}
		catch (RuntimeException re) {
			logger.error("get failed", re);
			throw re;
		}
	}

	@Override
	public OcDevices findByImei(String imei) {
		List<OcDevices> devicesList = findByProperty("imei", imei);
		if (devicesList!=null && devicesList.size() > 0) {
			return devicesList.get(0);
		}
		return null;
	}
	
	@Override
	public OcDevices findByAndroidID(String androidID) {
		List<OcDevices> devicesList = findByProperty("aid", androidID);
		if (devicesList!=null && devicesList.size() > 0) {
			return devicesList.get(0);
		}
		return null;
	}
	
	public List<OcDevices> findByProperty(String propertyName, Object value) {
		logger.debug("finding OcDevices instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from OcDevices as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		}
		catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}

	@Override
	public void update(OcDevices device) {
		getHibernateTemplate().update(device);
	}
	
}
